package com.jiyun.yonghu.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jiyun.vo.Result;
import com.jiyun.yonghu.domain.Permissions;
import com.jiyun.yonghu.domain.PermissionsVo;
import com.jiyun.yonghu.service.PermissionsService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("quanxian")
public class PermissionsController {
    @Autowired
    PermissionsService permissionsService;
    @RequestMapping("list")
    public Result list(@RequestBody Permissions menu){
        LambdaQueryWrapper<Permissions> qw = new LambdaQueryWrapper<>();
        qw.eq(StringUtils.isNotEmpty(menu.getName()),Permissions::getName,menu.getName());
        List<PermissionsVo> deptVoList = findByPid(permissionsService.list(qw), -1);
        return Result.seccuss(deptVoList);
    }

    private List<PermissionsVo> findByPid(List<Permissions> list, Integer pid) {
        ArrayList<PermissionsVo> deptVos = new ArrayList<>();

        for (Permissions menu : list) {
            if (menu.getPid().equals(pid)){
                PermissionsVo menuVo = new PermissionsVo();
                BeanUtils.copyProperties(menu,menuVo);
                List<PermissionsVo> vos = findByPid(permissionsService.list(), menu.getId());
                if (CollectionUtils.isNotEmpty(vos)){
                    menuVo.setChildren(vos);
                }
                deptVos.add(menuVo);
            }

        }
        return deptVos;
    }

    @RequestMapping("add")
    public Result add(@RequestBody Permissions permissions){
        return Result.seccuss(permissionsService.save(permissions));
    }
    @RequestMapping("update")
    public Result update(@RequestBody Permissions permissions){
        return Result.seccuss(permissionsService.updateById(permissions));
    }












    @RequestMapping("delete")
    public Result delete(@RequestParam Integer id){
        List<Permissions> menuList = permissionsService.list();
        List<Permissions> collect = menuList.stream().filter(menu -> menu.getPid() == id)
                .collect(Collectors.toList());
        if (collect.isEmpty()){
            return Result.seccuss(permissionsService.removeById(id));
        }
        return Result.errot();
    }
}
